import dayjs from 'dayjs';

const startTime = dayjs().startOf('day').toDate();
const endTime = dayjs().endOf('day').toDate();

export default async ({ args: { record }, context: { request } }) => {
	const {
		server: {
			app: {
				model: { Task },
			},
		},
	} = request;

	const pingTasks = {};
	const httpTasks = {};
	const pingTasksNameMap = {};
	const httpTasksNameMap = {};
	for await (const task of Task.find({
		refId: record._id,
		status: 'completed',
		endTime: { $gte: startTime, $lte: endTime },
		taskType: 'http',
	})) {
		const addition = task?.result?.addition || {};
		httpTasksNameMap[task.target] = task?.name;
		httpTasks[task.target] = (httpTasks[task.target] || []).concat(
			(addition?.nodeTotalCount - addition?.nodeAbnormalCount) /
				addition?.nodeTotalCount || 0
		);
	}

	for await (const task of Task.find({
		refId: record._id,
		status: 'completed',
		endTime: { $gte: startTime, $lte: endTime },
		taskType: 'ping',
	})) {
		const addition = task?.result?.addition || {};
		pingTasksNameMap[task.target] = task?.name;
		pingTasks[task.target] = (pingTasks[task.target] || []).concat(
			(addition?.nodeTotalCount - addition?.nodeAbnormalCount) /
				addition?.nodeTotalCount || 0
		);
	}

	const httpAvailablity = Object.entries(httpTasks).reduce(
		(res, [target, tasks]) => {
			const sum = tasks.reduce((s, num) => {
				s += num;
				return s;
			}, 0);
			res.push({
				target,
				taskType: 'HTTP',
				taskName: httpTasksNameMap[target],
				availability: sum / tasks.length || 0,
			});
			return res;
		},
		[]
	);

	const pingAvailablity = Object.entries(pingTasks).reduce(
		(res, [target, tasks]) => {
			const sum = tasks.reduce((s, num) => {
				s += num;
				return s;
			}, 0);
			res.push({
				target,
				taskType: 'Ping',
				taskName: pingTasksNameMap[target],
				availability: sum / tasks.length || 0,
			});
			return res;
		},
		[]
	);

	return httpAvailablity.concat(pingAvailablity);
};
